<?php
class ControllerCatalogSupplier extends AdminController {

  	public function index() {
  		M('catalog/supplier');
    	$this->getList();
  	}

  	public function insert() {
  		M('catalog/supplier');
		if ($this->request->isPost() && $this->validateForm()) {
			$this->model_catalog_supplier->addSupplier($this->request->post);
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/supplier'));
		}
    	$this->getForm();
  	}

  	public function update() {
  		M('catalog/supplier');
    	if ($this->request->isPost() && $this->validateForm()) {
			$this->model_catalog_supplier->editSupplier($this->request->get['supplier_id'], $this->request->post);
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/supplier'));
		}
    	$this->getForm();
  	}

  	public function delete() {
  		M('catalog/supplier');
    	if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $supplier_id) {
				$this->model_catalog_supplier->deleteSupplier($supplier_id);
			}
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/supplier'));
    	}

    	$this->getList();
  	}

  	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);
		
		$qf = new Query_filter();
		
		$total = $this->model_catalog_supplier->getTotalSuppliers($qf);
		$this->data['suppliers'] = $this->model_catalog_supplier->getSuppliers($qf);

		$this->data['keyword'] = $qf->get('keyword', '');
		
		$this->data['pagination'] = $this->pagination($total)->render();

		$this->display('catalog/supplier_list.tpl');
	}

  	protected function getForm() {
		$this->document->setTitle($this->_['heading_title']);
		$this->document->addScript(ROOT . 'static/javascript/jquery/jquery.validate.js');
		
		$supplier_id = G('supplier_id');
		if ($supplier_id) {
			$this->data['action'] = UA('catalog/supplier/update', "supplier_id=$supplier_id");
			if (!$this->request->isPost()) {
				$this->vo->data = $this->model_catalog_supplier->getSupplier($supplier_id);
			}
		} else {
			$this->data['action'] = UA('catalog/supplier/insert');
		}
		$this->display('catalog/supplier_form.tpl');
	}

	protected function validateForm() {
		$this->load->library('form_validation', true);
		$this->form_validation->set_rules('name', '', 'required|range_length[3,64]', $this->_['error_name']);
		return $this->form_validation->run();
	
	}
	
  	protected function validateDelete() {

		foreach ($this->request->post['selected'] as $supplier_id) {
  			$product_total = $this->model_catalog_supplier->getTotalProductBySupplierId($supplier_id);
			if ($product_total) {
	  			$this->setMessage('error_warning', sprintf($this->_['error_product'], $product_total));
				return FALSE;
			}
	  	}

		return TRUE;
  	}
}
?>